// client main.c
#include "my_header.h"
#include "transFile.h"
#include "connect.h"

int main(int argc, char *args[])
{
    // 192.168.238.128 12345
    ARGS_CHECK(argc, 3);
    int netfd = socket(AF_INET, SOCK_STREAM, 0);
    ERROR_CHECK(netfd, -1, "socket");
    printf("socket success\n");

    struct sockaddr_in server; // 绑定服务器
    server.sin_family = AF_INET;
    server.sin_port = htons(atoi(args[2]));
    int res = inet_aton(args[1], &server.sin_addr);
    // addr.sin_addr.s_addr = inet_addr(argv[1]);
    ERROR_CHECK(res, 0, "inet_aton");
    printf("client.ip  = %s\n", inet_ntoa(server.sin_addr));
    printf("client.port = %d\n", server.sin_port);
    res = connect(netfd, (struct sockaddr *)&server, sizeof(server));
    ERROR_CHECK(res, -1, "connect");
    printf("connect success\n");

    int epfd = epoll_create(1);
    epollAdd(epfd, STDIN_FILENO);
    epollAdd(epfd, netfd);
    struct epoll_event readyset[16];
    char buf[4096] = {0};
    while (1)
    {
        bzero(buf, sizeof(buf));
        int readynum = epoll_wait(epfd, readyset, 16, -1);
        for (int i = 0; i < readynum; ++i)
        {
            int cfd = readyset[i].data.fd;
            if (cfd == STDIN_FILENO) {
                ssize_t sret = read(STDIN_FILENO, buf, sizeof(buf));
                ERROR_CHECK(sret, -1, "STDIN recvMsg");
                if (sret > 0) {
                    buf[sret] = '\0';  // 确保 `buf` 是以 `\0` 结尾的字符串
                    strtok(buf, "\n"); // 去掉换行符
                    // printf("STDIN: sret = %ld, buf = %s\n", sret, buf);
                    sendMsg(netfd, buf);
                }
            }            
            else if (cfd == netfd)
            {
                // ssize_t sret = recvMsg(netfd, buf);
                // ERROR_CHECK(sret, -1, "netfd recvMsg");
                int ret = recvMsg(netfd ,buf);
                printf("server:%s\n", buf);// test recv msg from client

                // 收到空火车退出
                if(ret <= 0){
                    printf("client disconnect\n");
                    epollDel(epfd, netfd);
                    close(netfd);
                    return 0;
                }
            }
        }
    }
    return 0;
}